package com.weixun.cms.controller;


import com.jfinal.json.JFinalJson;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.weixun.cms.model.vo.Article;
import com.weixun.cms.model.vo.Channel;
import com.weixun.cms.service.ArticleService;
import com.weixun.cms.service.ChannelArticleService;
import com.weixun.cms.service.ChannelService;
import com.weixun.cms.service.SiteService;
import com.weixun.comm.controller.BaseController;
import com.weixun.comm.model.vo.Staff;
import com.weixun.model.CmsArticle;
import com.weixun.model.CmsChannel;
import com.weixun.model.CmsChannelArticle;
import com.weixun.utils.ajax.AjaxMsg;
import com.weixun.utils.beetl.BeetlUtils;
import com.weixun.utils.freemarker.FreemarkerUtils;
import com.weixun.utils.html.HtmlUtils;
import com.weixun.utils.record.RecordUtils;
import com.weixun.utils.time.DateUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ArticleController extends BaseController {

    ArticleService articleService = new ArticleService();
    SiteService siteService = new SiteService();
    ChannelService channelService = new ChannelService();
    ChannelArticleService channelArticleService = new ChannelArticleService();

    /**
     * 获取站点内容
     * @return
     */
    private Record  getsite()
    {
        List<Record>  records =siteService.findList("");
        return records.get(0);
    }

    /**
     * 获取栏目信息
     * @param channel_pk
     * @return
     */
    private CmsChannel getchannel(String channel_pk)
    {
        CmsChannel cmsChannel =channelService.findId(channel_pk);
        return cmsChannel;
    }

    /**
     * 基于layui的分页
     */
    public void pages(){
        int pageNumber = getParaToInt("page");
        int pageSize = getParaToInt("limit");
        String article_title = getPara("article_title");
        String channel_pk = getPara("channel_pk");
        Page<Record> list = articleService.paginate(pageNumber,pageSize,article_title,channel_pk);//获得用户信息
        renderPageForLayUI(list);
    }

    /**
     * 查询数据列表
     */
    public void list()
    {
        String article_pk = getPara("article_pk");
        List<Record> records = articleService.findList(article_pk);
//        renderJson(JFinalJson.getJson().toJson(records));
        setAttr("article", records.get(0));
        render("/views/cms/article/edit.jsp");
    }


    /**
     * 删除数据
     */
    public void delete()
    {
        AjaxMsg ajaxMsg = new AjaxMsg();
        String article_pk = this.getPara("article_pk");
        int res =articleService.deleteById(article_pk);
        if (res >0) {
            ajaxMsg.setState("success");
            ajaxMsg.setMsg("删除成功");
        }
        else
        {
            ajaxMsg.setState("fail");
            ajaxMsg.setMsg("删除失败");
        }

        renderJson(ajaxMsg);
    }

    /**
     * 根据文章id查询文章所在所有栏目的id
     */
    public  void ztree_checkd()
    {
        String article_pk=getPara("article_pk");
        List<CmsChannelArticle>  channelArticleList = channelArticleService.findList(article_pk,"");
        renderJson(JFinalJson.getJson().toJson(channelArticleList));
    }

    /**
     * 保存方法
     */
    public void saveOrUpdate()
    {
        AjaxMsg ajaxMsg = new AjaxMsg();
        boolean res = false;

        try {
//            String channel_pks = getPara("channel_pks");
//            CmsArticle cmsArticle = new CmsArticle();
            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            Staff staff = (Staff) session.getAttribute("loginUser");

            CmsArticle cmsArticle = getModel(CmsArticle.class,"");
            if (cmsArticle.getArticlePk() != null && !cmsArticle.getArticlePk().equals(""))
            {
                //判断是否设置了时间
                if (cmsArticle.getArticleSendtime() ==null || cmsArticle.getArticleSendtime().equals(""))
                {
                    cmsArticle.setArticleSendtime(DateUtil.getStringDate());
                }
                //文章更新者
                cmsArticle.setArticleUpauthor(staff.getStaff_name());
                res = cmsArticle.update();

            }
            else {
                //判断是否设置了时间
                if (cmsArticle.getArticleSendtime() ==null || cmsArticle.getArticleSendtime().equals(""))
                {
                    cmsArticle.setArticleSendtime(DateUtil.getStringDate());
                }
                //保存方法
                //文章更新者
                cmsArticle.setArticleAuthor(staff.getStaff_name());
                res = cmsArticle.save();
            }
            if(res)
            {
                /**
                 * 如果是更新文章
                 * 删除文章和栏目的关系
                 */
                if (cmsArticle.getArticlePk() != null && !cmsArticle.getArticlePk().equals("")) {
                    int result = channelArticleService.delete(cmsArticle.getArticlePk().toString());
                }
                /**
                 * 重新新建文章和栏目的关系
                 */
                String ids[] = cmsArticle.getFkChannelPk().split(",");
                for (String id : ids) {
                    CmsChannelArticle cmsChannelArticle = new CmsChannelArticle();
                    //返回插入成功后的主键值
                    cmsChannelArticle.setFkArticlePk(cmsArticle.getArticlePk().toString());
                    //栏目的id值
                    cmsChannelArticle.setFkChannelPk(id);
                    //保存文章栏目关联关系
                    cmsChannelArticle.save();
                }


                //生成内容页静态页
                createPage(cmsArticle.getArticlePk().toString(),ids);
                //生成列表静态页面
                createListPage(cmsArticle.getArticlePk().toString(),ids);

                ajaxMsg.setState("success");
                ajaxMsg.setMsg("保存成功");
            }
            else
            {
                ajaxMsg.setState("fail");
                ajaxMsg.setMsg("保存失败");
            }
        }catch (Exception e)
        {
            e.getMessage();
            ajaxMsg.setState("fail");
            ajaxMsg.setMsg("保存失败");
        }
        renderJson(ajaxMsg);
    }

    /**
     * 生存内容页
     * @param article_pk
     * @param ids
     */
    public void createPage(String article_pk,String ids[])
    {
        //根据发文栏目查找出该栏目下的文档
        for (String id : ids) {

            if (getchannel(id).getChannelPageTemplate()!=null && !getchannel(id).getChannelPageTemplate().equals("")) {
                //根据文档id查出文档详细内容列表
                Record record = articleService.findOne(article_pk);
                Map<String, Object> data = new HashMap<>();
                //将reord转化为bean
                Article article = RecordUtils.converModel(Article.class, record);
                data.put("article", article);
                data.put("channel", getchannel(id));
                /**
                 * 模板路径
                 * /template/qhrst
                 */
                String templatePath = getRequest().getSession().getServletContext().getRealPath(getsite().getStr("site_template"));
                /**
                 * 内容页模板文件
                 */
                String templateName = getchannel(id).getChannelPageTemplate();
                /**
                 * 生成html页面路径
                 */
                //String targetHtmlPath = getpath().getStr("site_static") + tmpchannel.getChannel_pages();
                String targetHtmlPath ="";
                        if(getchannel(id).getChannelPageName()!=null && !getchannel(id).getChannelPageName().equals("")) {
                            targetHtmlPath= getsite().getStr("site_static") + getchannel(id).getChannelCatalog() + getchannel(id).getChannelPageName();
                        }
                        else
                        {
                            targetHtmlPath= getsite().getStr("site_static") + getchannel(id).getChannelCatalog() + article_pk + ".html";
                        }

                /**
                 *调用生成模板的方法
                 */
                FreemarkerUtils.crateHTML(data, templatePath, templateName, targetHtmlPath);
            }
        }

    }

    /**
     * 生成栏目对应的列表页面
     * @param fk_article_pk 文章主键（未使用）
     * @param ids  栏目id集合
     *  由于根据栏目id获取文章列表
     *  故该方法未用到文章主键参数
     */
    public void createListPage(String fk_article_pk,String ids[])
    {

        List<Article> articleList = null;
        //根据发文栏目查找出该栏目下的文档
        for (String id : ids) {
            Record channelrecord = channelService.findById(id);
            Channel channel = RecordUtils.converModel(Channel.class,channelrecord);
            //查出栏目配置信息
            if (getchannel(id).getChannelListTemplate() != null && !getchannel(id).getChannelListTemplate().equals("")) {
                //根据栏目id获取栏目下面的文章列表
                List<CmsChannelArticle> cmsChannelArticles = channelArticleService.findList("", id);
                String article_pks = "";
                //获取文章id集合
                for (CmsChannelArticle cmsChannelArticle : cmsChannelArticles) {
                    article_pks += cmsChannelArticle.getFkArticlePk() + ",";
                }

                //根据文档id集合查出文档详细内容列表
                List<Record> records = articleService.findList(article_pks.substring(0, article_pks.length() - 1));
                Map<String, Object> data = new HashMap<>();
                articleList = new ArrayList<>();
                for (Record record : records) {
                    //实现records转化为model
                    Article article = RecordUtils.converModel(Article.class, record);
                    if (article.getArticle_content()!=null && !article.getArticle_content().equals(""))
                    {
                        article.setArticle_content(HtmlUtils.getNewContent(article.getArticle_content()));
                    }
                    articleList.add(article);
                }
                data.put("articlelist", articleList);
                data.put("channel", channel);
                /**
                 * 模板路径
                 * /template/qhrst
                 */
                String templatePath = getRequest().getSession().getServletContext().getRealPath(getsite().getStr("site_template"));
                /**
                 * 索引页模板文件
                 */
                String templateName = getchannel(id).getChannelListTemplate();
                /**
                 * 生成html页面路径
                 */
                //String targetHtmlPath = getpath().getStr("site_static") + tmpchannel.getChannel_pages();
                String targetHtmlPath = getsite().getStr("site_static") + getchannel(id).getChannelCatalog() + getchannel(id).getChannelListName();

                /**
                 *调用生成模板的方法
                 */
                FreemarkerUtils.crateHTML(data, templatePath, templateName, targetHtmlPath);
            }
        }

    }


}
